package fm.dongman.animefm.view.widget

import android.content.Context
import android.os.Handler
import android.os.Message
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.util.AttributeSet
import android.util.SparseArray
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.item_comic_latest_anime.view.*
import java.lang.ref.WeakReference

/**
 * banner 配合专属适配器使用 BannerViewPagerAdapter
 * Created by shize on 2017/10/20.
 */
class BannerViewPager constructor(context: Context, attrs: AttributeSet? = null)
    : ViewPager(context, attrs) {

    var mInterval: Long = 1000L // 滑动间隔，默认 1000 ms
    var mIsTouch: Boolean = false // 是否有操作
    private var mDirection: Int = View.FOCUS_RIGHT // 滑动方向，默认向右

    private val mChildrenViews = SparseArray<View>() // 存放子 view 的集合
    private val mHandler = BannerHandler(this)  // 初始化 handler
    private var mIsStop: Boolean = true // 是否被停滞了

    init {
        // 发送滑动请求
        mHandler.sendEmptyMessageDelayed(MSG_SCROLL, mInterval)
        offscreenPageLimit = 1
        // 控制是否自动切换
        this.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {
                when (state) {
                    SCROLL_STATE_IDLE -> {
                        mIsTouch = false
                    }
                    SCROLL_STATE_DRAGGING -> {
                        mIsTouch = true
                    }
                    SCROLL_STATE_SETTLING -> {
                        mIsTouch = true
                    }
                }
            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}

            override fun onPageSelected(position: Int) {
                mChildrenViews[currentItem].mRlFlyInText.startLayoutAnimation()
            }
        })
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        // 移除所以消息发送和回调
        mHandler.removeCallbacksAndMessages(null)
    }

    /**
     * 自动滑动页面
     */
    private fun AutoScrollPager() {
        if (mIsTouch || mIsStop) {
            return
        }
        scrollNext()
    }

    /**
     * 滑动到下一个页面
     */
    private fun scrollNext() {
        if (mChildrenViews.size() == 0) {
            return
        }
        if (currentItem + 1 < mChildrenViews.size()) {
            arrowScroll(mDirection)
        } else {
            currentItem = 0
        }
    }

    /**
     * 滑动到上一个页面
     */
    private fun scrollPrev() {
        if (mChildrenViews.size() == 0) {
            return
        }
        if (currentItem - 1 >= 0) {
            arrowScroll(mDirection)
        } else {
            currentItem = mChildrenViews.size() - 1
        }
    }

    /**
     * 给指定位置添加 view
     * @param view 视图
     * @param position 位置
     */
    fun addViewWithPosition(view: View, position: Int) = mChildrenViews.put(position, view)

    /**
     * 获取指定位置的 view
     * @param position 位置
     */
    fun getViewByPosition(position: Int) = mChildrenViews.get(position)

    /**
     * 停止自动切换
     */
    fun stopRunning() {
        mIsStop = true
    }

    /**
     * 开始自动切换
     * @param interval 间隔时间 ms
     */
    fun startRun(interval: Long) {
        mInterval = interval
        mIsStop = false
    }

    /**
     * 手动滑向下一个
     */
    fun next() {
        mIsStop = true
        scrollNext()
        mIsStop = false
    }

    /**
     * 手动滑向上一个
     */
    fun previous() {
        mIsStop = true
        scrollPrev()
        mIsStop = false
    }

    companion object {
        val MSG_SCROLL: Int = 0x01 // 滑动消息
    }

    class BannerHandler constructor(banner: BannerViewPager) : Handler() {
        private var mBanner: WeakReference<BannerViewPager> = WeakReference(banner)

        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            if (mBanner.get() == null || msg == null) {
                return
            }
            val banner: BannerViewPager = mBanner.get()!!
            when (msg.what) {
                MSG_SCROLL -> {
                    banner.AutoScrollPager()
                    sendEmptyMessageDelayed(MSG_SCROLL, banner.mInterval)
                }
            }
        }
    }

    /**
     * BannerViewPager 的专属适配器
     */
    abstract class BannerViewPagerAdapter : PagerAdapter() {
        override fun instantiateItem(container: ViewGroup?, position: Int): Any {
            return createPager(container, position)
        }

        override fun destroyItem(container: ViewGroup?, position: Int, `object`: Any?) {
            container?.removeView(`object` as View?)
        }

        abstract fun createPager(container: ViewGroup?, position: Int): View
    }
}